<template>
  <div class="search vH">
    <el-row>
      <mei-select
        ref="searchmodel"
        :data="sys4data_003"
        :loading="page.searchmodelloading"
        width="140px"
        v-model="page.searchmodel"
        size="small"
        filterable
        allow-create
        default-first-option
        style="margin-right:10px"
        @change="onModelChange"
      ></mei-select>
      <el-button
        type="primary"
        size="small"
        icon="el-icon-circle-check"
        @click="onSearchSave"
      >
        保存模板
      </el-button>
      <el-button size="small" icon="el-icon-circle-plus-outline">
        新建
      </el-button>
      <el-button size="small" icon="el-icon-remove-outline">
        删除
      </el-button>
    </el-row>
    <el-row class="main">
      <transition-group
        mode="out-in"
        appear
        enter-active-class="animated fadeInLeft"
        leave-active-class="animated fadeOutLeft"
      >
        <el-row
          type="flex"
          align="middle"
          style="padding-top: 10px"
          v-for="(item, index) in formItem"
          :key="item.keyname"
        >
          <el-col :span="5">{{ item.sysAssetA1.SYS_ASSET_A1_50 }}</el-col>
          <el-col :span="4">
            <el-select
              v-model="formItem[index].symbol"
              placeholder="请选择"
              style="width:100%"
            >
              <template v-for="symboltype in Object.keys(types)">
                <el-option
                  :key="symboltype"
                  v-if="formItem[index].types.includes(symboltype)"
                  :label="symboltype"
                  :value="types[symboltype]"
                  :name="types[symboltype]"
                ></el-option>
              </template>
            </el-select>
          </el-col>
          <el-col :span="12" style="padding-left:5px">
            <el-input
              v-model="formItem[index].value"
              v-nulltext
              v-if="
                !item.sysAssetA1.SYS_ASSET_A1_60 &&
                  item.sysAssetA1.SYS_ASSET_A1_170 != 'Date'
              "
            >
            </el-input>
            <el-date-picker
              v-if="
                !item.sysAssetA1.SYS_ASSET_A1_60 &&
                  item.sysAssetA1.SYS_ASSET_A1_170 == 'Date'
              "
              v-model="formItem[index].value"
              align="right"
              type="date"
              v-nulltext
              class="vWimp"
            >
            </el-date-picker>
            <assetA1Ddl
              v-else-if="item.sysAssetA1.SYS_ASSET_A1_60"
              v-model="formItem[index].value"
              :multiple="true"
              clearable
              :sysAssetA1="item.sysAssetA1"
            ></assetA1Ddl>
          </el-col>
          <el-col :span="3" style="padding-left:5px">
            <el-button
              type="primary"
              plain
              icon="el-icon-delete"
              @click="remove(item.keyname)"
            >
            </el-button
          ></el-col>
        </el-row>
      </transition-group>
    </el-row>
    <el-row class="foot tree_top_border">
      <el-button size="small" icon="el-icon-refresh-left" @click="onClear">
        清空查询
      </el-button>
      <el-button size="small" icon="el-icon-close" @click="onClose">
        关闭
      </el-button>
      <el-button
        size="small"
        type="primary"
        icon="el-icon-search"
        @click="onSearch"
      >
        查询
      </el-button>
    </el-row>
  </div>
</template>

<script>
import assetA1Ddl from "../assetA1Ddl.vue";
import { System4, AssetA1 } from "@/api";
import { isArray, isArrayEmpty } from "@/utils/validate";
export default {
  data() {
    return {
      types: {
        包含: "like",
        不包含: "not like",
        开始: "likestart",
        结束: "likeend",
        等于: "=",
        不等于: "!=",
        为空: "null",
        不为空: "notnull",
        大于: ">",
        大于等于: ">=",
        小于: "<",
        小于等于: "<=",
        包括: "in",
        不包括: "not in"
      },
      sysAssetA1Data: [], //字段数据
      formItem: [],
      sys4data_003: [],
      page: {
        searchmodelloading: false,
        searchmodel: ""
      }
    };
  },
  inject: ["AssetA1", "thisdialog"],
  //外部属性
  props: {},
  //内部方法
  methods: {
    async initPage() {
      //得到字段数据
      let sysAssetA1Data = await AssetA1.GetSysAssetA2();
      this.sysAssetA1Data = sysAssetA1Data;
      //查询模板
      this.page.searchmodelloading = true;
      let sys4data_003 = await System4.GetDDLitemBySys5code("003");
      this.sys4data_003 = sys4data_003;
      this.$nextTick(() => {
        this.page.searchmodelloading = false;
        this.$nextTick(() => {
          this.page.searchmodel = this.$refs.searchmodel.setSelectIndex(0);
          this.getItemByModel();
        });
      });
    },
    //添加项
    addItem(sysAssetA1, val = {}) {
      let symbol = val.symbol || "", //运算符
        name = "", //名
        value = val.value || "", //值
        types = ""; //运算类型
      //key
      const keyname = `${sysAssetA1.SYS_ASSET_A1_160}_${this.formItem.length}`;
      //哪个为true走哪个
      switch (true) {
        case sysAssetA1.SYS_ASSET_A1_170 == "Int" ||
          sysAssetA1.SYS_ASSET_A1_170 == "Date":
          types = [
            "等于",
            "不等于",
            "为空",
            "不为空",
            "大于",
            "大于等于",
            "小于",
            "小于等于"
          ];
          break;
        default:
          types = Object.keys(this.types).filter(item => {
            return !["包括", "不包括"].includes(item);
          });
      }
      //如果是关联 下拉 ：in || not in
      if (sysAssetA1.SYS_ASSET_A1_60) {
        types = ["包括", "不包括", "为空", "不为空"];
        value = value ? value.split(",") : [];
      }
      //添加项
      if (this.formItem.search({ keyname }).length == 0) {
        this.formItem.push({
          symbol: symbol || this.types[types[0]], //运算符的值
          name: sysAssetA1.SYS_ASSET_A1_160, //字段
          keyname, //组件ID
          value, //录入的值
          types, //运算类型
          sysAssetA1: sysAssetA1 //其他
        });
      }
      return keyname;
    },
    //通过查询模板 加载查询项
    async getItemByModel() {
      let sys4data = await System4.GetSys4ByCode(this.page.searchmodel);
      const items = JSON.parse(sys4data.System_4_50);
      let val = JSON.parse(sys4data.System_4_60);
      // console.log(sys4data);
      if (sys4data) {
        //先清空
        this.formItem.length = 0;
      }
      /**
       * 循环item 避免重复项丢失
       * System_4_50存项
       * System_4_60存值 {symbol,value}
       */
      items &&
        items.forEach((item, index) => {
          const thisval = val[index];
          //得到项
          let sysAssetA1 = this.sysAssetA1Data.find(
            a1 => a1.SYS_ASSET_A1_160 == item
          );
          if (sysAssetA1) {
            //添加项
            setTimeout(() => {
              this.addItem(sysAssetA1, thisval);
            }, 200 * index);
          }
        });
    },
    //删除项
    remove(keyname) {
      this.formItem.splice(
        this.formItem.findIndex(item => item.keyname === keyname),
        1
      );
    },
    //选择模板
    onModelChange() {
      this.getItemByModel();
    },
    //查询
    onSearch() {
      // console.log(this.formItem);
      const assetquery = this.formItem.map(({ symbol, name, value }) => {
        if (!isArray(value)) {
          value = [value.toString()];
        }
        return { symbol, name, value };
      });
      this.AssetA1.setAssetQuery(assetquery);
      this.thisdialog.close();
      // const res = await AssetA1.GetByQuery(assetquery);
      // res.strMS && this.$message(res.strMS);
    },
    onClear() {
      this.AssetA1.setAssetQuery([]);
      this.thisdialog.close();
    },
    onClose() {
      this.thisdialog.close();
    },
    //保存查询模板
    async onSearchSave() {
      let str50, str60;
      str50 = this.formItem.map(({ name }) => {
        return name;
      });
      str60 = this.formItem.map(({ symbol, value }) => {
        if (isArray(value)) {
          value = value.join(",");
        }
        return { symbol, value };
      });
      // console.log(str60);
      let res = await System4.Save(
        "003",
        this.$refs.searchmodel.getSeleteText(),
        JSON.stringify(str50),
        JSON.stringify(str60)
      );
      res.strMS && this.$message(res.strMS);
    }
  },
  //组件
  components: {
    assetA1Ddl
  },
  //初始化 异步加async await
  mounted() {
    this.initPage();
  },
  //计算属性
  computed: {},
  //监视
  watch: {}
};
</script>

<style lang="scss" scoped>
@import "@/style/base.scss";
.search {
  display: flex;
  flex-direction: column;
}
.main {
  flex: 1;
  padding-bottom: 10px;
  overflow: auto;
}
.foot {
  text-align: right;
}
.input-with-select {
  /deep/ .el-input-group__prepend {
    background-color: #fff;
  }
}
</style>
